<?php
/**
 * 用户操作
 */
namespace app\modules\controllers;
use yii\web\Controller;
use app\models\User;
use app\models\Profile;
use Yii;
use yii\data\Pagination;
class UserController extends Controller{
/**
 * 显示用户列表
 * @author  zhuojundu
 */
	public function actionUsers(){
		$this->layout = 'layout1';
		$query = User::find()->joinWith('profile');
		$count = $query->count();
		$pagesize = Yii::$app->params['pageSize']['user'];
		$pages = new Pagination(['totalCount'=>$count,'defaultPageSize'=>$pagesize]);
		$user = $query->offset($pages->offset)->limit($pages->limit)->all();
		return $this->render('users',['user'=>$user,'pages'=>$pages]);
	}

/**
 * 添加用户
 * @author  zhuojundu
 */	
	public function actionReg(){
		$this->layout = 'layout1';
		$model = new User;
		if(Yii::$app->request->isPost){
			$post = Yii::$app->request->post();
			// print_r($post);die;
			if($model->reg($post)){
				Yii::$app->session->setFlash('info','用户添加成功');
			}else{
				Yii::$app->session->setFlash('info','用户添加失败');
			}
		}
		$model->userpass = '';
		$model->repass = '';
		return $this->render('reg',['model'=>$model]);
	}

/**
 * 删除用户
 * @author  zhuojundu
 */
	public function actionDel(){
		try{
			$userid = Yii::$app->request->get('id');
			if(empty($userid)){
				Yii::$app->session->setFlash('info','用户id不能为空');
				throw new \Exception();
			}
			$trans = Yii::$app->db->beginTransaction();//加载事务
			if($obj = Profile::find()->where('userid =:id',[':id'=>$userid])->one()){
				$res = Profile::deleteAll('userid = :id',[':id'=>$userid]);
				if(empty($res)){
					Yii::$app->session->setFlash('info','profile表删除失败');
					throw new \Exception();
				}
			}
			if(!User::deleteAll('userid = :id',[':id'=>$userid])){
				Yii::$app->session->setFlash('info','user表删除失败');
				throw new \Exception();
			}
			Yii::$app->session->setFlash('info','删除成功');
			$trans->commit();
		}catch(\Exception $e){
			if(Yii::$app->db->getTransaction()){
				$trans->rollback();
			}
		}
		return $this->redirect(['user/users']);
	}

}